package com.csyf.manager.utils;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author: Enzo
 * @Date: 2018/11/22 16:13
 */

public class XmlHelpler {

    public static String xmlbuild(Map map) {

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("<xml>");
        Set<Map.Entry<String, String>> set = map.entrySet();
        for (Map.Entry<String, String> entry : set) {
            if (StringUtils.isNotBlank(entry.getValue())) {
                stringBuffer.append("<");
                stringBuffer.append(entry.getKey());
                stringBuffer.append("><![CDATA[");
                stringBuffer.append(entry.getValue());
                stringBuffer.append("]]></");
                stringBuffer.append(entry.getKey());
                stringBuffer.append(">");
            }

        }
        stringBuffer.append("</xml>");
        return stringBuffer.toString();
    }

    public static Map parseXml(String xml) {
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        Document document = null;
        try {
            document = DocumentHelper.parseText(xml);
            Element rootElement = document.getRootElement();

            List<Element> elements = rootElement.elements();

            for (Element ele : elements) {
                objectObjectHashMap.put(ele.getName(), ele.getText());
            }
            return objectObjectHashMap;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return objectObjectHashMap;
    }

    /**
     * 获取xml 文件中指定的节点
     * @param xml
     * @param elementName
     * @return
     */
    public static Map parseXmlByElement(String xml,String elementName) {
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        Document document = null;
        try {
            document = DocumentHelper.parseText(xml);
            Element rootElement = document.getRootElement();

            Element element = rootElement.element(elementName);
            List<Element> elements = element.elements();

            for (Element ele : elements) {
                objectObjectHashMap.put(ele.getName(), ele.getText());
            }
            return objectObjectHashMap;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return objectObjectHashMap;
    }
}
